package com.borya.util;

import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.borya.framework.util.ObjectUtils;
import com.borya.model.entity.Gps2Address;

public class TransAddr {

	private static Logger log = Logger.getLogger(TransAddr.class);

	public static void main(String[] args) throws Exception {
		// System.out.println("qq.maps._svcb3.geocoder0&&qq.maps._svcb3.geocoder0(".length());
		// System.out.println(getGpsInfo("30.591897", "104.062437"));
		Gps2Address gps2Address = new Gps2Address("30.591897", "104.062437");
		getAddress(gps2Address, Constant.ApiConf.BAIDU_MAP_APK);
		System.out.println(gps2Address.toString());
	}

	public static void getAddress(Gps2Address gps2Address, String baiduAk) {
		try {
			gps2Address.setAddress("");
			if (ObjectUtils.isNullOrEmpty(gps2Address.getLat()) || ObjectUtils.isNullOrEmpty(gps2Address.getLon())) {
				return;
			}
			StringBuilder sb = new StringBuilder(256);
			sb.append("http://api.map.baidu.com/geocoder/v2/?location=");
			sb.append(gps2Address.getLat()).append(",").append(gps2Address.getLon());
			sb.append("&output=json&ak=");
			sb.append(baiduAk);
			sb.append("&extensions_town=true");
			String res = HTTPUtils.sendGet(sb.toString());
			log.info("位置查询：send:" + sb.toString() + ",get:" + res);
			if (StringUtils.isNotBlank(res)) {
				JSONObject resJso = JSONObject.parseObject(res);
				if ("0".equals(resJso.getString("status"))) {
					JSONObject addJso = resJso.getJSONObject("result");
					final String addr = addJso.getString("formatted_address");
					JSONObject addressComponent = addJso.getJSONObject("addressComponent");
					final String p = addressComponent.getString("province");
					final String c = addressComponent.getString("city");
					JSONObject addressJso = new JSONObject();
					addressJso.put("p", p);
					addressJso.put("c", c);
					addressJso.put("addr", addr);
					gps2Address.setPro(p);
					gps2Address.setCity(c);
					gps2Address.setAddress(addr);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	// /**
	// * 位置不准
	// * @param lat
	// * @return
	// {"p":"四川省","c":"成都市","d":"武侯区","adcode":"510107","short_addr":"天益街83","addr":"四川省成都市武侯区天益街83"}
	// * @throws UnsupportedEncodingException
	// */
	// public static JSONObject getGpsInfo(String lat, String lon) throws
	// UnsupportedEncodingException {
	//
	// //
	// http://www.gpsspg.com/apis/maps/geo/?output=jsonp&lat=23.0300000000&lng=113.7500000000&type=0&callback=jQuery110208793408215097993_1524812057981&_=1524812057982
	// StringBuilder url = new StringBuilder(256);
	// url.append("http://apis.map.qq.com/jsapi?qt=rgeoc");
	// url.append("&lnglat=" + lon + "," + lat + "");
	// url.append("&key=FBOBZ-VODWU-C7SVF-B2BDI-UK3JE-YBFUS");
	// url.append("&output=jsonp&pf=jsapi&ref=jsapi&cb=qq.maps._svcb3.geocoder0");
	//
	// byte[] byteArray = HTTPUtils.sendGetReByte(url.toString());
	// String str = new String(byteArray, "GBK");
	// String substring = str.substring(str.indexOf("{"), str.length() - 1);
	// JSONObject parseObject = JSONObject.parseObject(substring);
	// if (parseObject != null) {
	// JSONObject detail = parseObject.getJSONObject("detail");
	// if (detail != null) {
	// JSONArray poilist = detail.getJSONArray("poilist");
	// if (poilist != null && poilist.size() > 0) {
	// JSONObject jsonObject = poilist.getJSONObject(0);
	// JSONObject addrInfo = jsonObject.getJSONObject("addr_info");
	// addrInfo.put("addr", jsonObject.get("addr"));
	// String p = addrInfo.getString("p");
	// String c = addrInfo.getString("c");
	// String addr = addrInfo.getString("addr");
	// if("".equals(p)){
	// if(addr.contains("北京市")||addr.contains("天津市")||addr.contains("上海市")||addr.contains("重庆市")){
	// p = addr.substring(0,3);
	// c = addr.substring(0,3);
	// }
	// else if(addr.contains("省")){
	// p = addr.substring(0,addr.indexOf("省")+1);
	// c = addr.substring(0,addr.indexOf("市")+1).substring(addr.indexOf("省")+1);
	//
	// }
	// addrInfo.put("p", p);
	// addrInfo.put("c", c);
	// }
	// return addrInfo;
	// }
	// }
	// }
	// return null;
	//
	// }

	/**
	 * 百度api
	 *
	 * @param lat
	 * @param lon
	 * @return
	 */
	public static GpsInfo address(String lat, String lon, String baiduAk) {
		if (Objects.isNull(lat) || Objects.isNull(lon)) {
			log.warn("获取百度地址经纬度为空,lat=" + lat + ",lon=" + lon);
			return null;
		}
		StringBuilder sb = new StringBuilder(256);
		sb.append("http://api.map.baidu.com/geocoder/v2/?location=");
		sb.append(lat).append(",").append(lon);
		sb.append("&output=json&ak=");
		sb.append(baiduAk);
		sb.append("&extensions_town=true&latest_admin=1");
		String res = HTTPUtils.sendGet(sb.toString());
		if (StringUtils.isNotBlank(res)) {
			JSONObject resJso = JSONObject.parseObject(res);
			if ("0".equals(resJso.getString("status"))) {
				JSONObject addJso = resJso.getJSONObject("result");
				JSONObject addressComponent = addJso.getJSONObject("addressComponent");
				GpsInfo info = new GpsInfo();
				info.setCity(addressComponent.getString("city"));
				info.setFormattedAddress(addJso.getString("formatted_address"));
				info.setProvince(addressComponent.getString("province"));
				info.setDistrict(addressComponent.getString("district"));
				return info;
			}
		}
		return null;
	}

	/**
	 * 反编译地址为经纬度
	 *
	 * @param baiduAk
	 * @param address
	 * @return
	 */
	public static GpsInfo geocoding(String baiduAk, String address) {
		if (Objects.isNull(address)) {
			log.warn("获取百度地址为空,address=" + address);
			return null;
		}
		StringBuilder sb = new StringBuilder(256);
		sb.append("http://api.map.baidu.com/geocoding/v3/?address=");
		sb.append(address);
		sb.append("&output=json&ak=");
		sb.append("7YcrSO3PXUkE0VNz7Or07nKt93AXwodE");// 秦波的key，30W额度
		String res = HTTPUtils.sendGet(sb.toString());
		if (StringUtils.isNotBlank(res)) {
			JSONObject resJso = JSONObject.parseObject(res);
			if ("0".equals(resJso.getString("status"))) {
				JSONObject addJso = resJso.getJSONObject("result");
				JSONObject location = addJso.getJSONObject("location");
				String lng = location.getString("lng");
				String lat = location.getString("lat");
				return address(lat, lng, baiduAk);
			}
		}
		return null;
	}

	public static class GpsInfo {
		String formattedAddress;
		String province;// ": "四川省",
		String city;// ": "成都市",
		String district;

		public String getFormattedAddress() {
			return formattedAddress;
		}

		public void setFormattedAddress(String formattedAddress) {
			this.formattedAddress = formattedAddress;
		}

		public String getProvince() {
			return province;
		}

		public void setProvince(String province) {
			this.province = province;
		}

		public String getCity() {
			return city;
		}

		public void setCity(String city) {
			this.city = city;
		}

		public String getDistrict() {
			return district;
		}

		public void setDistrict(String district) {
			this.district = district;
		}

		@Override
		public String toString() {
			return "[formattedAddress=" + formattedAddress + ", province=" + province + ", city=" + city + ", district="
					+ district + "]";
		}
	}

}